package com.iecg.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iecg.service.IecgMobileService;
import com.pig4cloud.pigx.common.core.exception.ValidateCodeException;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class IecgValidateCodeFilter  implements Filter {

	@Autowired
	private IecgMobileService mobileService;
    @Autowired
	private ObjectMapper objectMapper;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		try {
			String grantType = request.getParameter("grant_type");
			if(grantType !=null && "mobile".equals(grantType)){
				String mobile = request.getParameter("mobile");
				String code  = request.getParameter("code");
				if(!mobileService.checkCode(mobile, code)){
					throw new ValidateCodeException("验证码不合法");
				};
				RequestHolder.add(mobile);
			}
			String templateType = request.getParameter("template_type");
			if(templateType !=null){
				RequestHolder.add(templateType);
			}
			filterChain.doFilter(request, response);
		}catch (Exception e){
			try {
				response.getOutputStream().write(objectMapper.writeValueAsBytes(R.failed(e.getMessage())));;
			} catch (JsonProcessingException e1) {
				log.error("对象输出异常", e1);
			}
		}


	}

	@Override
	public void destroy() {

	}
}
